<?php
/**
 * Created by PhpStorm.
 * User: dongxiaofeng
 * Date: 2017/3/16
 * Time: 15:56
 */
namespace zhtfrontend\modules\sitepadapi\controllers;

use common\components\helpers\Fun;
use zhtfrontend\models\datas\ArrangeCourse;
use zhtfrontend\modules\sitepadapi\components\rest\ActiveController;
use yii\data\ArrayDataProvider;
use yii\db\Query;
use yii\filters\Cors;
use zhtfrontend\models\datas\Student;
use yii\web\Response;

class GrowthteachdiaryController extends ActiveController
{
    public $modelClass = 'zhtfrontend\models\datas\ClassLesson';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Allow-Origin' => ['*'],
                'Access-Control-Request-Method' => ['POST', 'PUT', 'GET', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 3600,
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],
        ];
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionGetclasslesson($user_id)
    {
        if (empty($user_id)) {
            return ['statusCode' => 200, 'message' => 'error', 'items' => '用户id不可为空'];
        }
        $admin = (new Query())->select('*')->from('{{%admin}}')
            ->where(['id' => $user_id])->one(Fun::getSiteDb());
        if (empty($admin) || empty($admin['teacher_id'])) {
            return ['statusCode' => 200, 'items' => null];
        }
        if ($admin['role'] == 'teache_teacher') {
            $class_manage_ids = $cl_resultdata = $dataArr = [];
            $teacher_id = $admin['teacher_id'];
            $goods_arrs = (new Query())->select(["goods_id", "max(IF(obj_type='class_count',value,'')) as class_count", "max(IF(obj_type='teacher_form',value,'')) as teacher_form", "max(IF(obj_type='teacher',attribute_id,'')) as teacher_id"])
                ->distinct()->from('{{%goods_attr}}')
                ->groupBy('goods_id')->having(['teacher_id' => $teacher_id])->all(Fun::getSiteDb());
            if (!empty($goods_arrs)) {
                foreach ($goods_arrs as $goodarr) {
                    $class_manage = (new Query())->select('*')->from('{{%class_manage}}')->where(['associate_id' => $goodarr['goods_id'], 'is_old' => 0, 'status' => 1])->one(Fun::getSiteDb());
                    if (!empty($class_manage)) {
                        $class_manage_ids[] = $class_manage['class_id'];
                    }
                }
                $class_lessons = (new Query())->select('*')->from('{{%class_lesson}}')->where(['in', 'class_id', $class_manage_ids])->andWhere(['not in', 'status', [2]])->all(Fun::getSiteDb());
                if (!empty($class_lessons)) {
                    foreach ($class_lessons as $class_lesson) {
                        $class_date = $this->getDay($class_lesson['class_date']);
                        $good = (new Query())->select(['picture'])->from('{{%goods}} g')->leftJoin('{{%class_manage}} cm', 'cm.associate_id = g.id')->where(['cm.class_id' => $class_lesson['class_id'], 'cm.is_old' => 0])->one(Fun::getSiteDb());
                        $class_lesson['picture'] = !empty($good) ? $good['picture'] : null;
                        $cl_resultdata[$class_date][] = [
                            'lesson_id' => $class_lesson['lesson_id'],
                            "class_id" => $class_lesson['class_id'],
                            "class_date" => $this->getDay($class_lesson['class_date']),
                            "start_time" => $this->getTime($class_lesson['start_time']),
                            "end_time" => $this->getTime($class_lesson['end_time']),
                            "lesson" => $class_lesson['lesson'],
                            "title" => $class_lesson['title'],
                            "status" => $class_lesson['status'],
                            "ovo" => $class_lesson['ovo'],
                            "info" => $class_lesson['info']
                        ];

                    }
                }
            }
            /*
             * 去获取艺教学的课程时间信息
             */
            $arrangements = (new Query())->select(['ar.*','a.*','c.name as course_name'])->from('{{%art_relation}} ar')
                ->leftJoin('{{%arrangement}} a','a.id = ar.arrangement_id')
                ->leftJoin('{{%course}} c','c.id = a.course_id')
                ->where(['a.teacher_id'=>$teacher_id])
                ->orderBy('ar.lesson ASC')
                ->all(Fun::getSiteDb());
            $class_manage_art_ids = [];
            if(!empty($arrangements)){
                foreach ($arrangements as $arrangement){
                    $class_manage_art = (new Query())->select('*')->from('{{%class_manage}}')->where(['associate_id' => $arrangement['art_teaching_id'], 'is_old' => 0, 'status' => 1,'type'=>2])->one(Fun::getSiteDb());
                    if (!empty($class_manage_art)) {
                        $class_manage_art_ids[] = $class_manage_art['class_id'];
                    }
                    $course_names[] = $arrangement['course_name'];
                }

                $class_lessons_art = (new Query())->select('*')->from('{{%class_lesson}}')->where(['in', 'class_id', $class_manage_art_ids])->andWhere(['not in', 'status', [2]])
                    ->andWhere(['title'=>$course_names])->all(Fun::getSiteDb());
                if (!empty($class_lessons_art)) {
                    foreach ($class_lessons_art as $class_lesson_art) {
                        $class_date = $this->getDay($class_lesson_art['class_date']);
                        //$good = (new Query())->select(['picture'])->from('{{%goods}} g')->leftJoin('{{%class_manage}} cm', 'cm.associate_id = g.id')->where(['cm.class_id' => $class_lesson['class_id'], 'cm.is_old' => 0])->one(Fun::getSiteDb());
                        //然后获取艺教学的相关信息
                        $class_lesson_art['picture'] = null;//艺教学没有图片显示
                        $cl_resultdata[$class_date][] = [
                            'lesson_id' => $class_lesson_art['lesson_id'],
                            "class_id" => $class_lesson_art['class_id'],
                            "class_date" => $this->getDay($class_lesson_art['class_date']),
                            "start_time" => $this->getTime($class_lesson_art['start_time']),
                            "end_time" => $this->getTime($class_lesson_art['end_time']),
                            "lesson" => $class_lesson_art['lesson'],
                            "title" => $class_lesson_art['title'],
                            "status" => $class_lesson_art['status'],
                            "ovo" => $class_lesson_art['ovo'],//艺教学也没有个一对一一对多的展示
                            "info" => $class_lesson_art['info']
                        ];

                    }
                }
            }


            ksort($cl_resultdata);
            foreach ($cl_resultdata as $ik => $iv) {
                $dataArr[] = [
                    'time' => $ik,
                    'item' => $cl_resultdata[$ik]
                ];
            }
            return new ArrayDataProvider([
                'allModels' => $dataArr,
                'pagination' => [
                    'pageSize' => 20
                ],
            ]);

        }elseif ($admin['role'] == 'class_teacher'){//针对班主任获取名下的开课课程列表
            $class_manage_ids = $cl_resultdata = $dataArr = [];
            $classteacher_id = $admin['teacher_id'];
            $teacher_ids = (new Query())->select('id')->from('{{%teacher}}')->where(['parent_id'=>$classteacher_id])->column(Fun::getSiteDb());
            $goods_arrs = (new Query())->select(["goods_id", "max(IF(obj_type='class_count',value,'')) as class_count", "max(IF(obj_type='teacher_form',value,'')) as teacher_form", "max(IF(obj_type='teacher',attribute_id,'')) as teacher_id"])
                ->distinct()->from('{{%goods_attr}}')
                ->groupBy('goods_id')->having(['teacher_id' => $teacher_ids])->all(Fun::getSiteDb());
            /*要将艺教学也作为正常的课程显示于成长日志中*/
            if (!empty($goods_arrs)) {
                foreach ($goods_arrs as $goodarr) {//这里的goodsid是针对的技教学和普通课程，对于艺教学不会从goods_arr中获取
                    $class_manage = (new Query())->select('*')->from('{{%class_manage}}')->where(['associate_id' => $goodarr['goods_id'], 'is_old' => 0, 'status' => 1,'type'=>1])->one(Fun::getSiteDb());
                    if (!empty($class_manage)) {
                        $class_manage_ids[] = $class_manage['class_id'];
                    }
                }
                $class_lessons = (new Query())->select('*')->from('{{%class_lesson}}')->where(['in', 'class_id', $class_manage_ids])->andWhere(['not in', 'status', [2]])->all(Fun::getSiteDb());
                if (!empty($class_lessons)) {
                    foreach ($class_lessons as $class_lesson) {
                        $class_date = $this->getDay($class_lesson['class_date']);
                        $good = (new Query())->select(['picture'])->from('{{%goods}} g')->leftJoin('{{%class_manage}} cm', 'cm.associate_id = g.id')->where(['cm.class_id' => $class_lesson['class_id'], 'cm.is_old' => 0])->one(Fun::getSiteDb());
                        $class_lesson['picture'] = !empty($good) ? $good['picture'] : null;
                        $cl_resultdata[$class_date][] = [
                            'lesson_id' => $class_lesson['lesson_id'],
                            "class_id" => $class_lesson['class_id'],
                            "class_date" => $this->getDay($class_lesson['class_date']),
                            "start_time" => $this->getTime($class_lesson['start_time']),
                            "end_time" => $this->getTime($class_lesson['end_time']),
                            "lesson" => $class_lesson['lesson'],
                            "title" => $class_lesson['title'],
                            "status" => $class_lesson['status'],
                            "ovo" => $class_lesson['ovo'],
                            "info" => $class_lesson['info']
                        ];

                    }
                }
            }
            /*
             * 去获取艺教学的课程时间信息
             */
            $arrangements = (new Query())->select(['ar.*','a.*','c.name as course_name'])->from('{{%art_relation}} ar')
                ->leftJoin('{{%arrangement}} a','a.id = ar.arrangement_id')
                ->leftJoin('{{%course}} c','c.id = a.course_id')
                ->where(['a.teacher_id'=>$teacher_ids])
                ->orderBy('ar.lesson ASC')
                ->all(Fun::getSiteDb());
            $class_manage_art_ids=[];
            if(!empty($arrangements)){
                foreach ($arrangements as $arrangement){
                    $class_manage_art = (new Query())->select('*')->from('{{%class_manage}}')->where(['associate_id' => $arrangement['art_teaching_id'], 'is_old' => 0, 'status' => 1,'type'=>2])->one(Fun::getSiteDb());
                    if (!empty($class_manage_art)) {
                        $class_manage_art_ids[] = $class_manage_art['class_id'];
                    }
                    $course_names[] = $arrangement['course_name'];
                }

                $class_lessons_art = (new Query())->select('*')->from('{{%class_lesson}}')->where(['in', 'class_id', $class_manage_art_ids])->andWhere(['not in', 'status', [2]])
                    ->andWhere(['title'=>$course_names])->all(Fun::getSiteDb());
                if (!empty($class_lessons_art)) {
                    foreach ($class_lessons_art as $class_lesson_art) {
                        $class_date = $this->getDay($class_lesson_art['class_date']);
                        //$good = (new Query())->select(['picture'])->from('{{%goods}} g')->leftJoin('{{%class_manage}} cm', 'cm.associate_id = g.id')->where(['cm.class_id' => $class_lesson['class_id'], 'cm.is_old' => 0])->one(Fun::getSiteDb());
                        //然后获取艺教学的相关信息
                        $class_lesson_art['picture'] = null;//艺教学没有图片显示
                        $cl_resultdata[$class_date][] = [
                            'lesson_id' => $class_lesson_art['lesson_id'],
                            "class_id" => $class_lesson_art['class_id'],
                            "class_date" => $this->getDay($class_lesson_art['class_date']),
                            "start_time" => $this->getTime($class_lesson_art['start_time']),
                            "end_time" => $this->getTime($class_lesson_art['end_time']),
                            "lesson" => $class_lesson_art['lesson'],
                            "title" => $class_lesson_art['title'],
                            "status" => $class_lesson_art['status'],
                            "ovo" => $class_lesson_art['ovo'],//艺教学也没有个一对一一对多的展示
                            "info" => $class_lesson_art['info']
                        ];

                    }
                }
            }

            ksort($cl_resultdata);
            foreach ($cl_resultdata as $ik => $iv) {
                $dataArr[] = [
                    'time' => $ik,
                    'item' => $cl_resultdata[$ik]
                ];
            }
            return new ArrayDataProvider([
                'allModels' => $dataArr,
                'pagination' => [
                    'pageSize' => 20
                ],
            ]);
        }
    }

    protected function getTime($time)
    {
        $currentTime = strlen($time) == 3 ? substr($time, 0, 1) . ':' . substr($time, 1) : substr($time, 0, 2) . ':' . substr($time, 2);
        return $currentTime;
    }

    protected function getDay($day)
    {
        return \Yii::$app->formatter->asDate($day, 'yyyy-MM-dd');
    }

    /*
     * 获取上节课每个学生的喜爱程度
     */
    public function actionGetlastlessonscore($lesson_id)
    {
        if (empty($lesson_id)) {
            return ['statusCode' => 200, 'items' => null];
        }
        /*
         * $pre_lesson_replys 上堂课作品反馈
         * $pre_lessonenjoyscore 上堂课的喜欢度
         */
        $pre_lesson_students = $enjoyclassscore = $pre_lesson_replys = [];
        $pre_lessonenjoyscore = [];
        $pre_lesson_reply = [];
        $current_lesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['lesson_id' => $lesson_id])->one(Fun::getSiteDb());
        if (!empty($current_lesson)) {
            if ($current_lesson['lesson'] > 1) {
                //有可能上节课是延课延到最后了，所以最好是找上一节正常的课程
                $pre_lesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['not in', 'status', [2]])->andWhere(['<', 'lesson', $current_lesson['lesson']])
                    ->andWhere(['class_id' => $current_lesson['class_id']])->orderBy(['lesson' => SORT_DESC])->one(Fun::getSiteDb());
            } else {
               //$pre_lesson = null;
                $pre_lesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['not in', 'status', [2]])->andWhere(['=', 'lesson', $current_lesson['lesson']])
                    ->andWhere(['class_id' => $current_lesson['class_id']])->orderBy(['lesson' => SORT_DESC])->one(Fun::getSiteDb());
            }
            if (!empty($pre_lesson)) {
                $pre_lesson_students = (new Query())->select('*')->from('{{%lesson_student}} ls')->where(['lesson_id' => $pre_lesson['lesson_id']])->all(Fun::getSiteDb());

                if (!empty($pre_lesson_students)) {
                    foreach ($pre_lesson_students as $k => $pre_lesson_student) {
                        $command = \Yii::$app->db->createCommand("SELECT * FROM {{%student}} WHERE id=:student_id");
                        $command->bindValue(':student_id', $pre_lesson_student['student_id']);
                        $student = $command->queryOne();
                        $customer_command = \Yii::$app->db->createCommand("SELECT logo FROM {{%customer}} WHERE id=:customer_id");
                        $customer_command->bindValue(':customer_id', $student['customer_id']);
                        $customer = $customer_command->queryOne();
                        /*上堂课喜欢度*/
                        $enjoyclassscore['teacher_score'] = $pre_lesson_student['teacher_score'];
                        $enjoyclassscore['student_name'] = $student['name'];
                        $enjoyclassscore['student_logo'] = $customer['logo'];
                        $pre_lessonenjoyscore[] = $enjoyclassscore;
                        /*上堂课作品反馈*/
                        $pre_lesson_reply['student_id'] = $student['id'];
                        $pre_lesson_reply['student_name'] = $student['name'];
                        $pre_lesson_reply['student_logo'] = $customer['logo'];
                        $pre_lesson_reply['refouce_notice'] = $pre_lesson_student['refouce_notice'];//家长的提问
                        $pre_lesson_reply['refouce_answer'] = !empty($pre_lesson_student['refouce_answer']) ? $pre_lesson_student['refouce_answer']:'';//老师的回复
                        $pre_lesson_reply['refouce_score'] = $pre_lesson_student['refouce_score'];//老师对作品的打分
                        //这个课下练习应该是家长端传送的吧
                        $lesson_medias = (new Query())->select(['me.file_path as file_path', 'me.type as type', 'me.alt as alt', 'me.is_default as is_default', 'lm.status as status'])->from('{{%lesson_media}} lm')
                            ->leftJoin('{{%medias}} me', 'me.object_id=lm.id')
                            ->where(['lm.student_id' => $pre_lesson_student['student_id'], 'lm.is_refouce' => 1])//is_refouce0为花絮1为课下练习
                            ->andWhere(['in', 'lm.lesson_id', [$pre_lesson_student['lesson_id']]])
                            ->andWhere(['like', 'me.class_name', '%LessonMedia', false])
                            ->all(Fun::getSiteDb());
                        $pre_lesson_reply['medias'] = $lesson_medias;
                        $pre_lesson_replys[] = $pre_lesson_reply;
                    }
                }
            }
            $lesson_fouces = $lesson_fouce = $learn_evaluations = $learn_evaluation = $current_lesson_tidbits = $current_lesson_tidbit = [];
            $current_lesson_content = '';
            $current_lesson_students = (new Query())->select('*')->from('{{%lesson_student}} ls')->where(['lesson_id' => $current_lesson['lesson_id']])->all(Fun::getSiteDb());
            if (!empty($current_lesson_students)) {
                foreach ($current_lesson_students as $current_lesson_student) {
                    $command = \Yii::$app->db->createCommand("SELECT * FROM {{%student}} WHERE id=:student_id");
                    $command->bindValue(':student_id', $current_lesson_student['student_id']);
                    $student = $command->queryOne();
                    $customer_command = \Yii::$app->db->createCommand("SELECT logo FROM {{%customer}} WHERE id=:customer_id");
                    $customer_command->bindValue(':customer_id', $student['customer_id']);
                    $customer = $customer_command->queryOne();
                    /*
                     * 本节课课下练习重点
                     */
                    $lesson_fouce['student_id'] = $student['id'];
                    $lesson_fouce['student_name'] = $student['name'];
                    $lesson_fouce['student_logo'] = $customer['logo'];
                    $lesson_fouce['lesson_fouce'] = $current_lesson_student['lesson_fouce'];
                    if (!empty($current_lesson_student['lesson_content'])) {
                        $current_lesson_content = $current_lesson_student['lesson_content'];
                    }
                    $lesson_fouces[] = $lesson_fouce;
                    /**
                     * 学习评价
                     */
                    $learn_evaluation['student_id'] = $student['id'];
                    $learn_evaluation['student_name'] = $student['name'];
                    $learn_evaluation['student_logo'] = $customer['logo'];
                    $learn_evaluation['lesson_score'] = $current_lesson_student['lesson_score'];
                    $learn_evaluations[] = $learn_evaluation;
                    /*
                     * 作品花絮
                     */
                    $current_lesson_tidbit['student_id'] = $student['id'];
                    $current_lesson_tidbit['student_name'] = $student['name'];
                    $current_lesson_tidbit['student_logo'] = $customer['logo'];
                    $lesson_tidbit_medias = (new Query())->select(['me.file_path as file_path', 'me.type as type', 'me.alt as alt', 'me.is_default as is_default', 'lm.status as status'])->from('{{%lesson_media}} lm')
                        ->leftJoin('{{%medias}} me', 'me.object_id=lm.id')
                        ->where(['lm.student_id' => $current_lesson_student['student_id'], 'lm.is_refouce' => 0])//is_refouce0为花絮1为课下练习
                        ->andWhere(['in', 'lm.lesson_id', [$current_lesson_student['lesson_id']]])
                        ->andWhere(['like', 'me.class_name', '%LessonMedia', false])
                        ->all(Fun::getSiteDb());
                    $current_lesson_tidbit['medias'] = $lesson_tidbit_medias;
                    $current_lesson_tidbits[] = $current_lesson_tidbit;
                }
            }
            $teache_form = '';
            switch ($current_lesson['ovo']) {
                case 0:
                    $teache_form = '一对一教学';
                    break;
                case 1:
                    $teache_form = '小班制教学';
                    break;
                case 2:
                    $teache_form = '普通制教学';
                    break;
                default:
                    $teache_form = '普通制教学';
            }
            $data = [
                'pre_lteache_formessonenjoyscore' => $pre_lessonenjoyscore,
                'pre_lesson_replys' => $pre_lesson_replys,
                'current_lesson_content' => $current_lesson_content,//本节课学习内容 这个应该放到class_lesson表里面吧？？现在是一堂课一个学习内容，不是一个学生一个学习内容，唉，乱七八糟的先就这样吧
                'lesson_fouces' => $lesson_fouces,
                'learn_evaluations' => $learn_evaluations,
                'current_lesson_tidbits' => $current_lesson_tidbits,//花絮
                'teache_form' => $teache_form,
                'start_time' => $this->getTime($current_lesson['start_time']),
                'end_time' => $this->getTime($current_lesson['end_time'])
            ];
            return ['statusCode' => 200, 'items' => $data];
        } else {
            return ['statusCode' => 200, 'items' => null];
        }
    }

    /**
     * 成长日志的表单提交啥的
     */
    public function actionUpdatediary($lesson_id, $student_id = '')
    {
        if (\Yii::$app->request->post() != null) {
            $data = \Yii::$app->request->post();
            $refouceAnswer = array_key_exists('refouce_answer', $data) ? $data['refouce_answer'] : '';//教师对上堂课作品反馈的问题回复
            $lessonContent = array_key_exists('lesson_content', $data) ? $data['lesson_content'] : '';
            $lessonScorearr = array_key_exists('lessonScores', $data) ? $data['lessonScores'] : '';
            if (!empty($lesson_id)) {
                if (!empty($student_id)) {
                    $lessonStudent = (new Query())->select('*')->from('{{%lesson_student}}')
                        ->where(['lesson_id' => $lesson_id, 'student_id' => $student_id])
                        ->one(Fun::getSiteDb());
                    if (empty($lessonStudent['refouce_answer']) || ($lessonStudent['refouce_answer'] != $refouceAnswer && !empty($refouceAnswer))) {
                        //注意这里是针对上堂课的更新
                        $current_lesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['lesson_id' => $lesson_id])->one(Fun::getSiteDb());
                        $pre_lesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['not in', 'status', [2]])->andWhere(['<', 'lesson', $current_lesson['lesson']])
                            ->andWhere(['class_id' => $current_lesson['class_id']])->orderBy(['lesson' => SORT_DESC])->one(Fun::getSiteDb());
                        Fun::getSiteDb()->createCommand()->update('{{%lesson_student}}', [
                            'refouce_answer' => $refouceAnswer
                        ], ['lesson_id' => (int)$pre_lesson['lesson_id'], 'student_id' => $student_id])->execute();
                    }
                }
                if (empty($lessonStudent['lesson_content']) || ($lessonStudent['lesson_content'] != $lessonContent && !empty($lessonContent))) {
                    if (!empty($student_id)) {
                        Fun::getSiteDb()->createCommand()->update('{{%lesson_student}}', [
                            'lesson_content' => $lessonContent,
                        ], ['lesson_id' => $lesson_id, 'student_id' => $student_id])->execute();
                    } else {
                        Fun::getSiteDb()->createCommand()->update('{{%lesson_student}}', [
                            'lesson_content' => $lessonContent,
                        ], ['lesson_id' => $lesson_id])->execute();
                    }

                }
                if (!empty($lessonScorearr)) {
                    foreach ($lessonScorearr as $lessonScore) {
                        Fun::getSiteDb()->createCommand()->update('{{%lesson_student}}', [
                            'lesson_score' => (int)$lessonScore['lesson_score']
                        ], ['lesson_id' => $lesson_id, 'student_id' => $lessonScore['student_id']])->execute();
                    }
                }
                return ['statusCode' => 200, 'items' => $data];
            }
        } else {
            return ['statusCode' => 200, 'items' => null];
        }
    }

    /*上传花絮文件*/
    public function actionUploadtidbitmedia($lesson_id, $student_id, $is_refouce)
    {
        /*将medias表添加对应的记录，添加啥呢我也母鸡一会看看*/
        $is_refouce = (integer)$is_refouce;
        $this->getSiteDb(Fun::getSiteId());
        $lm = (new Query())->select('*')->from('{{%lesson_media}}')->where(['student_id' => $student_id, 'lesson_id' => $lesson_id, 'is_refouce' => $is_refouce])->one();
        $media_type = 1;
        $postdata = \Yii::$app->request->post();
        if (!empty($lm)) {
            $insert_lesson_id = $lm['id'];
        } else {
            \Yii::$app->db->createCommand()->insert('{{%lesson_media}}', [
                'lesson_id' => $lesson_id,
                'student_id' => $student_id,
                'm_type' => 0,//没啥用就写上
                'is_refouce' => $is_refouce,
                'status' => 1
            ])->execute();
            $insert_lesson_id = \Yii::$app->db->getLastInsertID();
        }

        //$refouceAnswer = array_key_exists('refouce_answer', $postdata) ? $postdata['refouce_answer'] : '';
        $before_media_ids = (new Query())->select('id')->from('{{%medias}}')->where(['class_name' => 'zhtfrontend\models\datas\LessonMedia', 'object_id' => $insert_lesson_id])->column();
        $existed_media_ids = [];
        // $
        foreach ($postdata as $data) {
            if ($data['student_id'] == $student_id) {
                $ossmedias = $data['medias'];
                if (!empty($ossmedias)) {
                    foreach ($ossmedias as $media) {
                        $existed_media = (new Query())->select('*')->from('{{%medias}}')->where(['class_name' => 'zhtfrontend\models\datas\LessonMedia', 'object_id' => $insert_lesson_id, 'file_path' => $media['file_path']])->one();
                        if (!empty($existed_media)) {
                            $existed_media_ids[] = $existed_media['id'];
                        } else {//表中本来不存在那就要进行添加了
                            $fileType = strtolower(strrchr($media['file_path'], '.'));
                            if (in_array($fileType, \Yii::$app->params['aliyunoss']['videoAllowFiles'])) {
                                $media_type = 2;
                            }
                            \Yii::$app->db->createCommand()->insert('{{%medias}}', [
                                'class_name' => 'zhtfrontend\models\datas\LessonMedia',
                                'object_id' => $insert_lesson_id,
                                'file_path' => $media['file_path'],
                                'created_at' => time(),
                                'type' => $media_type//1 图片 2 视频
                            ])->execute();
                        }
                    }
                    //将已有的被去掉的媒体记录删除掉
                    $needdelete_mediaids = array_diff($before_media_ids, $existed_media_ids);
                    \Yii::$app->db->createCommand()->delete('{{%medias}}', ['in', 'id', $needdelete_mediaids])->execute();

                }
            }
        }
        return ['statusCode' => 200, 'items' => null];
    }

    protected function getSiteDb($site_id)
    {
        $site_cache = Fun::cache('site_cache');
        foreach ($site_cache as $k => $v) {
            if ($site_id == $v['id']) {
                $site = $v['domain'];
            }
        }
        if ($site == null) return false;
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['db'])) return false;
        \Yii::$app->set('db', $site_cache[$site]['db']);
    }

}